<?php namespace App\Admin\Orders\Shopping;

//基础条件
use App\Core\Repository\Criterias\InCriteria;
use App\Core\Repository\Criterias\FixedCriteria;
use App\Core\Repository\Criterias\PaginateCriteria;
use App\Core\Repository\Criterias\SortCriteria;
//过滤器
use App\Core\Repository\Criterias\Filters\InputCriteria;
use App\Core\Repository\Criterias\Filters\InputKeywordsCriteria;
use App\Core\Repository\Criterias\Filters\InputTimeRangeCriteria;

use Input;
use DB;
use App\Admin\User\User\Repository as UserRepository;
use App\Admin\Logistics\Delivers\Repository as DeliversRepository;
use App\Admin\Supplier\Supplier\Repository as SupplierRepository;
use App\Admin\Logistics\Logistics\Repository as LogisticsRepository;
require_once app_path().'/Library/excel/PHPExcel.php';

trait Service {
    
    //基础服务
    use \App\Core\Service\Service;
    use \App\Core\Service\Services\All;
    use \App\Core\Service\Services\Indexer;
    use \App\Core\Service\Services\Creater;
    use \App\Core\Service\Services\Updater;
    use \App\Core\Service\Services\Changer;
    use \App\Core\Service\Services\Deleter;
    use \App\Core\Service\Services\Detailer;
    //操作日志
    use \App\Admin\Base\LogService;
    
    protected function bootService(){
        $this->bootBaseService();
        $this->setRepository(new Repository);
        $this->setMeta(new Meta);
        $this->repository = $this->getRepository();
    }
	
    //列表
    public function lists(){
        //过滤器
        $conditions = [
            new InputTimeRangeCriteria('created_at'),
            new InputCriteria('status'),
            new InputCriteria('supplier_id'),
            new FixedCriteria('type', '4')
        ];
        $count = $this->repository->addCriterias($conditions)->count();
        $conditions[] = new PaginateCriteria();
        $conditions[] = new SortCriteria('id', 'desc');
        $data = $this->repository->resetQuery()->resetCriteria()->addCriterias($conditions)->all();
        $data->load('user','delivers');
        foreach ($data as $v){
            $order_info = $v->order_info;
            $consignee_info = $v->consignee_info;
            //商品信息
            if($order_info!=null){
                $order_infos = json_decode($order_info);
                $v->order_info = $order_infos;
            }else{
                $v->order_info = [];
            }
            //收货人信息
            if($consignee_info!=null){
                $consignee_infos=json_decode($consignee_info);
                $v->consignee_info = $consignee_infos;
            }else{
                $v->consignee_info = [];
            }
        }
        return $this->success([
            'count' => $count,
            'data' => $data
        ]);
    }


    public function createlogistics(){
        $order_id = Input::get('order_id');
        $deliver_id = Input::get('deliver_id');
        $deliver_no = Input::get('deliver_no');
        $user_id = Input::get('user_id');

        $delivers = with(new DeliversRepository)->addCriteria(new FixedCriteria('id', $deliver_id))->first();
        if($delivers){
            $deliver_code=$delivers->code;

            $this->repository->addCriteria(new FixedCriteria('id', $order_id))->update([
                'deliver_status' => '1',
                'deliver_id' => $deliver_id,
                'deliver_code' => $deliver_code,
                'deliver_no' => $deliver_no,
            ]);
            $logisticsRepository = new LogisticsRepository();
            $model = $logisticsRepository->addCriteria(new FixedCriteria('order_id', $order_id))->first();
            if($model){
                $model->deliver_id = $deliver_id;
                $model->deliver_code = $deliver_code;
                $model->deliver_no = $deliver_no;
                $model->save();
            }else{
                $logisticsRepository->resetQuery()->create([
                    'order_id' => $order_id,
                    'user_id' => $user_id,
                    'deliver_id' => $deliver_id,
                    'deliver_code' => $deliver_code,
                    'deliver_no' => $deliver_no,
                ]);
            }
            return $this->success();
        }
        return $this->inputError('非法操作');
    }
    

    public function multiExport(){
        $begin_time = strtotime($_GET['begin_time']);
        $end_time = strtotime($_GET['end_time']);
        $status = $_GET['status'];
        //$supplier_id = $_GET['supplier_id'];

        $curTime = time();

        $orders = DB::table('orders');
        if($begin_time > 0 && $curTime > $begin_time){
            $orders->where('start_time','>',$begin_time);
        }
        if($end_time > 0 && $curTime > $end_time){
            $orders->where('start_time','<',$end_time+24*3600);
        }
        if($status){
            $orders->where('status','=',$status);
        }
//        if($supplier_id){
//            $orders->where('supplier_id','=',$supplier_id);
//        }
        $orders = $orders->where('type','=',4)
            ->where('is_delete','=',0)
            ->orderBy('id','desc')
            ->get();
        if(count($orders)<=0){
            return $this->inputError('没有记录');
        }

        $sumprice = 0; //总金额
        $sumnum = 0; //总件数
        $stepfee = 0; //运动总优惠
        $enterprisefee = 0; //企业福利总抵减
        foreach($orders as $v){
            if(!$v){
                continue;
            }
            //用户昵称
            $user_id = $v->user_id;
            $v->userNickname = '暂无';
            if($user_id){
                $user = with(new UserRepository)->addCriteria(new FixedCriteria('id', $user_id))->first();
                if($user && $user->nickname){
                    $v->userNickname = $user->nickname;
                }
            }

            //备注
            if($v->message==null){
                $v->message = '暂无';
            }

            //供应商
//            $supplierId = $v->supplier_id;
//            if($supplierId!=null){
//                $supplier = with(new SupplierRepository)->addCriteria(new FixedCriteria('id', $supplierId))->first();
//                if($supplier->name!=null){
//                    $v->supplier_id = $supplier->name;
//                }else{
//                    $v->supplier_id = '暂无';
//                }
//            }else{
//                $v->supplier_id = '暂无';
//            }

            //物流信息
            $deliver_id = $v->deliver_id;
            $deliver_no = $v->deliver_no;
            if($deliver_id=='0' || $deliver_no==null){
                $v->deliver_id = '物流公司：暂无，运单号：暂无';
            }else{
                $delivers = with(new DeliversRepository)->addCriteria(new FixedCriteria('id', $deliver_id))->first();
                $v->deliver_id = '物流公司：'.$delivers->name."\r".'运单号：'.$deliver_no;
            }

            //商品信息
            $order_info = $v->order_info;
            if($order_info!=null){
                $order_infos=json_decode($order_info);
                $returnStr = '';

                $returnStr .= '运动优惠：'.$v->step_fee.'元'."\r";
                $returnStr .= '企业福利抵减：'.$v->enterprise_fee.'元'."\r";
                foreach ($order_infos as $index){
                    if(!empty($index->specStr) && isset($index->specStr)){
                        $returnStr .= '名称：'.$index->name.'，规格：'.$index->specStr.'，价格：'.$index->price.'，数量：'.$index->num.'。'."\r";
                        $v->order_info = $returnStr;
                    }else{
                        $returnStr .= '名称：'.$index->name.'，规格：默认，价格：'.$index->price.'，数量：'.$index->num.'。'."\r";
                        $v->order_info = $returnStr;
                    }
                }
            }else{
                //异常订单
                continue;
            }

            //收货人信息
            $consignee_info = $v->consignee_info;
            if($consignee_info!=null){
                $consignee_infos=json_decode($consignee_info,true);
                $userName = $consignee_infos['userName'];
                $telNumber = $consignee_infos['telNumber'];
                $address = '';
                if(isset($consignee_infos['provinceName'])){
                    $address .= $consignee_infos['provinceName'];
                }
                if(isset($consignee_infos['cityName'])){
                    $address .= $consignee_infos['cityName'];
                }
                if(isset($consignee_infos['countyName'])){
                    $address .= $consignee_infos['countyName'];
                }
                if(isset($consignee_infos['detailInfo'])){
                    $address .= $consignee_infos['detailInfo'];
                }
                $v->consignee_info = '姓名：'.$userName."\r".'电话：'.$telNumber."\r".'地址：'.$address;
            }else{
                $v->consignee_info = '暂无信息';
            }

            $v->start_time = date("Y-m-d H:i:s",$v->start_time);
            $status = $v->status;
            //订单状态
            if($status == 1){
                $v->status = '待支付';
            }else if($status == 2){
                $v->status = '支付完成';
            }else if($status == 3){
                $v->status = '订单完成';
            }else if($status == 4){
                $v->status = '失败';
            }

            $sumprice += $v->amount;//总金额
            $sumnum += $v->total;//总数量
            $stepfee += $v->step_fee;//运动总优惠
            $enterprisefee += $v->enterprise_fee;//企业福利总抵减
            $Totaldiscount = $stepfee+$enterprisefee;//总优惠
            $payment = $sumprice-$stepfee-$enterprisefee;
        }

        //实例化
        $objPHPExcel = new \PHPExcel();
        /*右键属性所显示的信息*/
        $objPHPExcel->getProperties()->setCreator("csk")  //作者
        ->setLastModifiedBy("csk")  //最后一次保存者
        ->setTitle('商城订单导出')  //标题
        ->setSubject('商城订单导出') //主题
        ->setDescription('导出数据')  //描述
        ->setKeywords("excel")   //标记
        ->setCategory("result file");  //类别

        //设置当前的表格
        $objPHPExcel->setActiveSheetIndex(0);

        if($_GET['status']==1){
            $status = '待支付';
        }else if($_GET['status']==2){
            $status = '支付完成';
        }else if($_GET['status']==3){
            $status = '订单完成';
        }else if($_GET['status']==4){
            $status = '失败';
        }else{
            $status = '所有状态';
        }
        $pre = '';
        if($_GET['begin_time'] && $_GET['end_time']){
            $pre = $_GET['begin_time'].'到'.$_GET['end_time'].'-';
        }else if(!$_GET['begin_time'] && !$_GET['end_time']){
            $pre = '全部时间-';
        }else if($_GET['begin_time'] && !$_GET['end_time']){
            $pre = $_GET['begin_time'].'之后-';
        }else if(!$_GET['begin_time'] && $_GET['end_time']){
            $pre = $_GET['end_time'].'之前-';
        }

        $filename = $pre.$status.'商城订单.xls';
        $title = $pre.$status.'的商城订单 总金额为：'.$sumprice.'元，总优惠为：'.$Totaldiscount.'元，实付：'.$payment.'元，总数量为：'.$sumnum;

        //处理表头标题
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//垂直居中
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
        $objPHPExcel->getActiveSheet()->mergeCells('A1:I1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1',$title);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);//加粗

        // 设置表格第二行显示内容
        $objPHPExcel->getActiveSheet()
            ->setCellValue('A2', '序号')
            ->setCellValue('B2', '昵称')
            ->setCellValue('C2', '订单号')
            ->setCellValue('D2', '备注')
            ->setCellValue('E2', '商品信息')
            ->setCellValue('F2', '收货人信息')
            ->setCellValue('G2', '运单信息')
            ->setCellValue('H2', '订单创建时间')
            ->setCellValue('I2', '订单状态');

        $key = 2;
        foreach($orders as $v){
            //设置循环从第三行开始
            $v->userNickname = $this->filterEmoji($v->userNickname);
            $key++;
            $objPHPExcel->getActiveSheet()
            //Excel的第A列，name是你查出数组的键值字段，下面以此类推
            ->setCellValue('A'.$key, $v->id)
            ->setCellValue('B'.$key, $v->userNickname)
            ->setCellValue('C'.$key, $v->wxorder)
            ->setCellValue('D'.$key, $v->message)
            ->setCellValue('E'.$key, $v->order_info)
            ->setCellValue('F'.$key, $v->consignee_info)
            ->setCellValue('G'.$key, $v->deliver_id)
            ->setCellValue('H'.$key, $v->start_time)
            ->setCellValue('I'.$key, $v->status);
        }

        //设置当前的表格
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel'); //文件类型
        header('Content-Disposition: attachment;filename='.$filename.''); //文件名
        header('Cache-Control: max-age=0');
        header('Content-Type: text/html; charset=utf-8'); //编码
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        ob_start();
        $objWriter->save('php://output');
        $xlsData = ob_get_contents();
        ob_end_clean();

        return $this->success([
         'filename' => $filename,
         'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
        ]);

    }
    //过滤emoji表情
    public function filterEmoji($emojiStr){
        $emojiStr = preg_replace_callback('/./u',function(array $match){
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },$emojiStr);
        return $emojiStr;
    }




}